package bank.driver.soap;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import bank.Account;
import bank.Bank;
import bank.InactiveException;
import bank.OverdrawException;
import bank.driver.soap.jaxws.BankService;
import bank.driver.soap.jaxws.BankServiceImplService;
import bank.driver.soap.jaxws.IOException_Exception;
import bank.driver.soap.jaxws.IllegalArgumentException_Exception;
import bank.driver.soap.jaxws.InactiveException_Exception;
import bank.driver.soap.jaxws.OverdrawException_Exception;

final public class SOAPBank implements Bank {

	private BankService port;

	public SOAPBank() {
		BankServiceImplService service = new BankServiceImplService();
		port = (BankService) service.getBankServiceImplPort();
	}

	@Override
	public Account getAccount(String number) throws IOException {
		return new SOAPAccount(port, number);
	}

	@Override
	public String createAccount(String owner) throws IOException {
		return port.createAccount(owner);
	}

	@Override
	public Set<String> getAccountNumbers() throws IOException {
		Set<String> set = new HashSet<String>();
		for (Object s : port.getAccountNumbers()) {
			set.add((String) s);
		}

		return set;
	}

	@Override
	public boolean removeAccount(String number) throws IOException {
		return port.removeAccount(number);
	}

	@Override
	public void transfer(Account a, Account b, double amount)
			throws IOException, IllegalArgumentException, OverdrawException,
			InactiveException {
		try {
			port.transfer(a.getNumber(), b.getNumber(), amount);
		} catch (IOException_Exception e) {
			throw new IOException(e.getMessage());
		} catch (IllegalArgumentException_Exception e) {
			throw new IllegalArgumentException(e.getMessage());
		} catch (InactiveException_Exception e) {
			throw new InactiveException(e.getMessage());
		} catch (OverdrawException_Exception e) {
			throw new OverdrawException(e.getMessage());
		}
	}
}
